const os = require("os")
const path = require("path")
const fs = require("fs")
const chalk = require("chalk")

class Utils {
  constructor() {
    this.str = ""
    this.print = console.log
  }

  async log(data) {
    this.str += `${data}`
    this.print(`${data}`)
  }

  async exit(ans) {
    let filename = this.parseTime(Date.now()) + '.txt'
    let logFile = path.join(os.tmpdir(), filename)
    fs.writeFileSync(logFile, this.str, {mode: '0766'})
    let exit = (code) => {
      if (code != 0) { //异常退出
        let msg = chalk.red(`${ans.name} create failed, more details please see ${chalk.underline(logFile)}\n`)
        this.print(`${msg}`)
        return
      }
      // 组合package.js路径
      let packageFile = path.join(process.cwd(), ans.name, 'package.json')
      // 获取package.json文件数据
      let res = fs.readFileSync(packageFile).toString()
      let data = JSON.parse(res)
      // 修改数据
      data.name = ans.name
      data.author = ans.author
      data.description = ans.description
      data.version = ans.version
      // 重新写入数据
      data = JSON.stringify(data)
      fs.writeFileSync(packageFile, data, {mode: '0755'})
      this.print(chalk.green(`project ${ans.name} created done \n`))

    }
    return exit
  }

  parseTime(time) {
    let date = new Date(time)

    function fillZero(num) {
      if (num < 10) {
        return '0' + num
      } else {
        return '' + num
      }
    }

    let y = date.getFullYear()
    let m = fillZero(date.getMonth() + 1)
    let d = fillZero(date.getDate())
    return `${y}_${m}_${d}_${time}`
  }
}

module.exports = Utils
